package com.template.templateuser.auth.serviceauth.filters;

import com.template.templateuser.common.constants.UserConstants;
import com.template.templateuser.common.exception.exceptions.AuthenticaException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;

public class VerifyCodeFilter extends OncePerRequestFilter {
    @Autowired
    private AuthenticationFailureHandler failureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {
        try {
        if (StringUtils.equals("/authentication/form", request.getRequestURI())
                && StringUtils.equalsIgnoreCase("post", request.getMethod()))
            validate(request);
        } catch (AuthenticaException verifyCodeException) {
            //失败调用我们的自定义失败处理器
            failureHandler.onAuthenticationFailure(request, response,verifyCodeException );
            //后续流程终止
            return;
        }
        filterChain.doFilter(request, response);

    }
    private void validate(HttpServletRequest request) throws ServletRequestBindingException {
        // 拿到之前存储的imageCode信息
        //ServletWebRequest swr = new ServletWebRequest(request);
       // ImageCaptchaVo imageCodeInSession = (ImageCaptchaVo) sessionStrategy.getAttribute(swr, CaptchaController.IMAGE_CAPTCHA_SESSION_KEY);
        //String codeInRequest = ServletRequestUtils.getStringParameter(request, "imageCode");
        HttpSession session=request.getSession();
        String verify_code=request.getParameter("verify_code");
        String session_verify_code=(String)session.getAttribute("UserConstants.VERIFYCODE_SESSION_PRIFIXX");
        if (StringUtils.isBlank(verify_code)) {
            throw new AuthenticaException("验证码的值不能为空");
        }
        Optional.ofNullable(session_verify_code).ifPresent(code->
            System.out.println("验证码不存在")
        );
        if (verify_code == null) {
            throw new AuthenticaException("验证码不存在");
        }
        if (session.isNew()) {
            session.removeAttribute(UserConstants.VERIFYCODE_SESSION_PRIFIXX);
            throw new AuthenticaException("验证码已过期");
        }
        if (!StringUtils.equals(verify_code, session_verify_code)) {
            throw new AuthenticaException("验证码不匹配");
        }
        //验证通过 移除缓存
        session.removeAttribute(UserConstants.VERIFYCODE_SESSION_PRIFIXX);
    }

}
